<template>
	<div id="content-wrapper" class="disFlex vertical">
		<Spin fix v-show="spinShow"></Spin>
		<div class="form-wrapper">
		   <Form  ref="formValidate" :label-width="120" :model="formValidate" :rules="ruleValidate" label-position="left">
		        <FormItem label="商户号" prop="shop_num">
		            <Input v-model="formValidate.shop_num" placeholder="请输入您的商户号"></Input>
		        </FormItem>
    		        <FormItem label="API密钥" prop="api_secret">
		            <Input v-model="formValidate.api_secret" type="password" placeholder="请输入您的API密钥"></Input>
		        </FormItem>
		        <FormItem label="安全证书KEY" prop="security_key">
		            <div class="input-wrapper">
						<Input readonly	v-model="formValidate.security_key" placeholder="点击开始上传证书" style="cursor: pointer;"></Input>
						<input class="upload-input" name="security_key" type="file" @change='handleFileChange'></input>
		            </div>
		        </FormItem>
		        <FormItem label="安全证书 CERT" prop="security_cert">
					<div class="input-wrapper">
						<Input readonly v-model="formValidate.security_cert" placeholder="点击开始上传证书" style="cursor: pointer;"></Input>
						<input class="upload-input" name="security_cert" type="file" @change='handleFileChange'></input>
		            </div>
		        </FormItem>
				<FormItem label="申请类型" prop="access_api_pay_wechatapp_parent">
					<RadioGroup v-model="formValidate.access_api_pay_wechatapp_parent">
						<Radio label="111">服务商模式</Radio>
						<Radio label="0">个人申请</Radio>
					</RadioGroup>
		        </FormItem>
		        <!--<FormItem label="企业付款 PEM" prop="security_pem">
		        		<div class="input-wrapper">
		           		 <Input readonly v-model="formValidate.security_pem" placeholder="点击开始上传证书" style="cursor: pointer;"></Input>
		            		<input class="upload-input" name="security_pem" type="file" @change='handleFileChange'></input>
		            </div>
		            <p>参数配置前请先 PKCS#1 转 PKCS#8，具体方法详见微信支付官方文档<a target="_blank" href="https://open.api.banchengyun.com/wechatApi/payTransferToBankRSA?appId=44&appToken=a56f9673549BVrOWl6pkqxygPMC2OpZozupXcdwTQT3M&wechatId=a20b01cb925pRYqwgZ5cTz1YQA2WJl4DwQK47pmOhFH4o">点击获取 PEM 公钥</a></p>
		        </FormItem>-->
		        <FormItem >
		            <Button type="primary" :loading="saveLoading" @click="handleSubmit('formValidate')">
		            		<!--<span v-if="!submitLoading">提交</span>
	        				<span v-else>提交中...</span>-->
	        				提交
		            </Button>
		        </FormItem>
		        
		   </Form>
		</div>
		<div class="form-wrapper">
			<div class="hexiao" v-if="openFn">
		   		<div class="item disFlex Flex-middle" style="margin-top: 24px;">
		   			<div class="item-title" style="width: 128px;padding: 10px 12px 10px 0;">店铺二维码配置</div>
		   			<Input v-if="codeSet.qrcode_to_miniprogram_link" v-model="codeSet.qrcode_to_miniprogram_link.shop_qrcode_to_miniprogram_link" placeholder="" />
		   		</div> 
		   		<div class="item disFlex Flex-middle" style="margin-top: 24px;">
		   			<div class="item-title" style="width: 128px;padding: 10px 12px 10px 0;">新核销二维码配置</div>
		   			<Input v-if="codeSet.qrcode_to_miniprogram_link" v-model="codeSet.qrcode_to_miniprogram_link.consume_code_qrcode_to_miniprogram_link" placeholder="" />
		   		</div> 
		   		<div class="item disFlex Flex-middle" style="margin-top: 24px;">
		   			<div class="item-title" style="width: 128px;padding: 10px 12px 10px 0;">开启新核销二维码</div>
		   			<Switch v-model="codeSet.is_new_consume_code" />
		   		</div>
		   		<div class="item disFlex Flex-middle" style="margin-top: 24px;margin-bottom: 24px;">
		   			<div class="item-title" style="width: 128px;padding: 10px 12px 10px 0;"></div>
		   			<Button type="primary" @click="codeSaveFn">保存</Button>
		   		</div>
			</div>
		</div>
	</div>
</template>

<script>
	import { uploadFile } from 'api/uploadFile'
    import { getWxpaySetting, saveWxpaySetting, getCodeSet, codeSetUpdate } from 'api/setting'

	export default {
        data () {
            return {
				wechat_id: -1,
				// 二维码配置
				codeSet: {
					qrcode_to_miniprogram_link: {
						shop_qrcode_to_miniprogram_link: "",
						consume_code_qrcode_to_miniprogram_link: ""
					}
				},

				spinShow: false,
				saveLoading: false,
				formValidate: {
                    shop_num: '',
                    api_secret: '',
                    security_key: '',
                    security_cert: '',
					security_pem: '',
					access_api_pay_wechatapp_parent: "111"
                },
                ruleValidate: {
                    shop_num: [
                        { required: true, message: '商户号不能为空', trigger: 'blur' }
                    ],
                    api_secret: [
                        { required: true, message: 'API密钥不能为空', trigger: 'blur' }
                    ],
                    security_key: [
                        { required: true, message: '请添加安全证书KEY', trigger: 'blur' }
                    ],
                    security_cert: [
                        { required: true, message: '请添加安全证书CERT', trigger: 'blur' }
					],
					access_api_pay_wechatapp_parent: [
                        { required: true, message: '请选择申请类型', trigger: 'change' }
                    ],
//                  security_pem: [
//                      { required: true, message: '请添加企业付款PEM', trigger: 'blur' }
//                  ]
				}
            	}
        },
        computed: {
        	openFn: function(argument) {
        		return true
        		let wechat_id = this.wechat_id
        		let off = false
        		if(this.codeSet){
        			off = true
        		}
        		return (wechat_id == 153 || wechat_id == 163 || wechat_id == 287 || wechat_id == 276 || wechat_id == 130 || wechat_id == 198 || wechat_id == 229 || wechat_id == 221 || wechat_id == 234 || wechat_id == 207) && off
        	}
        },
        methods: {     		
			handleFileChange (event) {
				this.spinShow = true;
			uploadFile(event.target.files[0]).then(fileUrl => {
					this.spinShow = false;
				this.formValidate[event.target.name] = fileUrl;
			}).catch(err => {
					this.spinShow = false;
				this.$Message.error(err.message);	
			}) 

			},

			handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
						this.saveData();
                    } else {
                        this.$Message.error('请填写完整信息!');
                    }
                })
            },
            getData() {
				this.spinShow = true;
				getWxpaySetting().then(_res=>{
					this.spinShow = false;
					var parms = {};
					parms.shop_num = _res.data.config.access_api_pay_wechatapp_id;
					parms.api_secret = _res.data.config.access_api_pay_wechatapp_key;
					parms.security_key = _res.data.config.access_api_pay_wechatapp_pem_key;
					parms.security_cert = _res.data.config.access_api_pay_wechatapp_pem_cert;
					parms.access_api_pay_wechatapp_parent = _res.data.config.access_api_pay_wechatapp_parent+"";
//      				parms.security_pem = _res.data.config.accessApiPayWechatappPemBank;
					this.formValidate = parms;
					
					this.wechat_id = _res.data.config.wechat_id
				}).catch(err => {
					this.spinShow = false;
				this.$Message.error(err.message);	
				})
				getCodeSet().then(_data => {
					
					if(_data.data.config.is_new_consume_code == 1){
						_data.data.config.is_new_consume_code = true
					}else {
						_data.data.config.is_new_consume_code = false
					}

					if(!_data.data.config.qrcode_to_miniprogram_link){
						_data.data.config.qrcode_to_miniprogram_link = {
							shop_qrcode_to_miniprogram_link: '',
							consume_code_qrcode_to_miniprogram_link: '',
						}
					}else {
						_data.data.config.qrcode_to_miniprogram_link = JSON.parse(_data.data.config.qrcode_to_miniprogram_link)
					}

					this.codeSet = _data.data.config
					
				}, _err => {
					console.log(_err)
				})
        	},
            saveData () {
            		this.saveLoading = true;
            		var parms = {};
            		parms.accessApiPayWechatappId = this.formValidate.shop_num;
            		parms.accessApiPayWechatappKey = this.formValidate.api_secret;
            		parms.accessApiPayWechatappPemKey = this.formValidate.security_key;
					parms.accessApiPayWechatappPemCert = this.formValidate.security_cert;
					parms.accessApiPayWechatappParent = parseInt(this.formValidate.access_api_pay_wechatapp_parent);
//          		parms.accessApiPayWechatappPemBank = this.formValidate.security_pem;
					// parms.debug = true;
            		// console.log(parms)
            		saveWxpaySetting(parms).then(_res=>{
   					this.$Message.success('保存成功');	
	        			this.saveLoading = false;
        			}).catch(err => {
	        			this.saveLoading = false;
   					this.$Message.error(err.message);	
				}) 
            },
            // 新核销设置保存
            codeSaveFn(){
            	let _data = JSON.parse(JSON.stringify(this.codeSet))
            	if(_data.is_new_consume_code){
            		_data.is_new_consume_code = 1
            	}else {
            		_data.is_new_consume_code = 0
            	}

            	_data.qrcode_to_miniprogram_link = JSON.stringify(_data.qrcode_to_miniprogram_link)

            	codeSetUpdate(_data).then(_res => {
					if(_res.status == 'ok'){
						this.$Message.success('保存成功');	
					}
				}, _err => {
					console.log(_err)
				})
            }
        },
        created() {
        		this.getData()
        },
        components: {
		}
     }
</script>

<style scoped>
	#content-wrapper {
		position: relative;
		width: auto;
		/* height: 100%; */
		background: white;
		padding: 20px 20px;
		padding-bottom: 0;
		/*margin: 12px 20px 12px 12px;*/
		display: flex;
	}
	.form-wrapper {
		flex: 0.6;
	}
</style>

<style type="text/css" scoped>
	.ivu-form .ivu-form-item-label {
		font-size: 13px;
	}
	input[type=text]:read-only {
		border-color: #ccc;
		background-color: #f8f8f8;
	}
	.input-wrapper {
		position: relative;
	}
	.input-wrapper .upload-input {
		position: absolute;
		left: 0;right: 0;
		bottom: 0;top: 0;
		opacity: 0;
	}
</style>